﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace HomeRun.DB
{
  public class HomeRunDB
  {
    private HomeRun.DB.DataSet.HomeRun data;
    private Dictionary<string, Dictionary<string, Type>> structure;
    private string openedFileName;
    private static HomeRunDB instance=null;

    private HomeRunDB()
    {
      data = new DataSet.HomeRun();
      structure = new Dictionary<string, Dictionary<string, Type>>();
      foreach (DataTable table in data.Tables)
      {
        Dictionary<string, Type> columnInfo = new Dictionary<string, Type>();
        foreach (DataColumn col in table.Columns)
        {
          columnInfo[col.ColumnName] = col.DataType;
        }
        structure[table.TableName] = columnInfo;
      }
    }

    public static HomeRunDB Instance
    {
      get
      {
        HomeRunDB retValue = instance;
        if (retValue == null)
        {
          retValue = new HomeRunDB();
        }
        return retValue;
      }
    }

    public void InitialHomeRunDB(string fileName)
    {
      try
      {
        data.ReadXml(fileName);
        openedFileName = fileName;
      }
      catch (Exception ex)
      {
        //todo throw a eception , call can not be InitialHomeRunDB

      }

    }

    public void SaveHomeRunDB()
    {
      if (openedFileName == string.Empty)
      {
        //create a default savefilename
        //set openedfile to the created name
      }
      try
      {
        data.WriteXml(openedFileName);
      }
      catch (Exception ex)
      {
        //todo throw a eception , call can not be saved HomeRunDB

      }

    }

    public bool checkStructure(string tableName,string columnName,string columnType)
    {
      bool retValue = checkStructure(tableName, columnName);
      if (retValue)
      {
        retValue = structure[tableName][columnName].ToString() == columnType;
      }
      return retValue;
    }

    public bool checkStructure(string tableName, string columnName)
    {
      bool retValue = checkStructure(tableName);
      if (retValue)
      {
        retValue = structure[tableName].Keys.Contains(columnName);
      }
      return retValue;
    }

    public bool checkStructure(string tableName)
    {
      return  structure.Keys.Contains(tableName);
    }

    internal HomeRun.DB.DataSet.HomeRun Data
    {
      get { return data; }
    }
  }
}
